package lee.vioson.remotedata

import lee.vioson.remotedata.config.HttpConfig
import lee.vioson.remotedata.interceptors.CommonRequestInterceptor
import lee.vioson.remotedata.interceptors.HttpLoggingInterceptor
import lee.vioson.remotedata.utils.HttpsUtils
import lee.vioson.repository.BuildConfig
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import java.util.logging.Level

/**
 *Author:viosonlee
 *Date:3/22/21
 *DESCRIPTION:
 */
class RetrofitManager {
    private val retrofit: Retrofit
        get() {
            return Retrofit.Builder()
                .baseUrl(EvnConstants.evn.baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build()
        }
    private val okHttpClient: OkHttpClient //可以添加拦截器
        get() {
            val builder = OkHttpClient.Builder()
            builder.addInterceptor(CommonRequestInterceptor())
            if (BuildConfig.DEBUG) {
                builder.addNetworkInterceptor(
                    HttpLoggingInterceptor("HTTP")
                        .apply {
                            setPrintLevel(HttpLoggingInterceptor.Level.BODY)
                            setColorLevel(Level.INFO)
                        })
            }
            val sslParams: HttpsUtils.SSLParams = HttpsUtils.getSslSocketFactory()
            builder.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
            builder.connectTimeout(HttpConfig.connectTimeout, TimeUnit.SECONDS)
            builder.readTimeout(HttpConfig.readTimeout, TimeUnit.SECONDS)
            builder.writeTimeout(HttpConfig.writeTimeout, TimeUnit.SECONDS)
            builder.hostnameVerifier(HttpsUtils.UnSafeHostnameVerifier)
            return builder.build()
        }

    fun <T> getApi(clazz: Class<T>): T {
        return retrofit.create(clazz)
    }
}